
  /*global $ returnCitySN require ClipboardJS wx err process*/
import axios from 'axios'
import Qs from 'qs'
import router from '../router'
import store from '../store'
import uuidv4 from 'uuid/v4';
import {getCookie, getUrlParam, saveCookie, removeCookie} from "../service/util.service";
import {getUA} from "../service/util.helper";
// const uuidv5 = require('uuid/v5');

// 特殊需求：特殊渠道ID优先接入
const specialChannelId = getUrlParam('specialChannelId') || 0;

// $instance基本配置
let $instance = axios.create({
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  },
  withCredentials: false,
  data: {}
});

// 全局axios配置
$instance.defaults.baseURL = (process.env.NODE_ENV === 'production') ? 'https://admin.zd-dqd.com/api.php' : 'https://admin.zd-dqd.com/api.php';
$instance.defaults.timeout = 6000;
// 额外自定义参数
$instance.retry = 1;
$instance.retryDelay = 1000;
$instance.__retryCount = 0;

$instance.setParams = (posted = false, query = {}) => {
  console.log(process.env.NODE_ENV)
  let user = store.state.auth.user;
  
  // 全局需要    
  // $instance.defaults.data.token = (user && user.token) ? user.token : ((user && user.token) ? user.token : (query.token ? query.token : (query.token ? query.token : '')));
  $instance.defaults.data.guide = specialChannelId ? specialChannelId : ((user && user.base_guide) ? user.base_guide : ((getCookie('guide') !== undefined && getCookie('guide') !== null) ? getCookie('guide') : 0));

  // $instance.defaults.data.task_id = (user && user.task_id) ? user.task_id : '';
  // $instance.defaults.data.user_id = (user && user.user_id) ? user.user_id : ((user && user.id) ? user.id : 0);
  // $instance.defaults.data.user_level = (user && user.level) ? user.level : 0;

  Object.assign($instance.defaults.data, store.state.global.params);

  // 全局设置session_id
  if ($instance.session_id === undefined && posted) {
    window.uuid = getCookie('uuid') ? getCookie('uuid') : uuidv4().replace(/-/g, '');
    $instance.session_id = window.uuid;
    saveCookie('uuid', window.uuid);
  }
  return $instance.defaults.data;
};

$instance.setParams(true);

// POST传参序列化
$instance.interceptors.request.use((config) => {
  if (typeof config.data === 'string') {
    config.baseURL = '';
    return config;
  }

  let query = {};
  query = router.app.$route.query
  $instance.setParams(false,query);
  Object.assign($instance.defaults.data, config.data);
  Object.assign(config.data, $instance.defaults.data);
  // cookie被清理，分页请求需要登录的跳转到登录页面
  if (router.app.$route.meta.auth && !(store.state.auth.user)) {
    return window.location.href = '/auth/login';
  }

  if (config.method.toLowerCase() === 'post') config.data = Qs.stringify(config.data, {skipNulls: true});
  return config;
}, (error) => {
  // 错误的传参
  return Promise.reject(error);
});

// 响应拦截器配置
$instance.interceptors.response.use((response) => {
  if (response.data && (response.data.code === 401)) {
    removeCookie('user');

    // 进入页面的调试
    // window.location.pathname = '/login';
  } else if (response.data.code === -2) {
    // setTimeout(() => {
    //   router.push({path: '/login'})
    // }, 500)
  } else if (response.data.code === 4000) {
    window.scrollTo(0,0)
    router.push({
      path: '/',
      query: router.app.$route.query
    })
  }
  return response;
}, function (error) {
  // console.log(error);
  // console.log(error.name); // ReferenceError
  // console.log(error.message); // lalala is not defined
  // console.log(error.stack); // ReferenceError: lalala is not defined at ...

  // 对响应错误做点什么
  store.dispatch('dingtalk', {
    tag: '接口请求异常:',
    url: location.origin + (error.config ? error.config.url : ''),
    reTry: $instance.__retryCount,
    content: error.toString(),
  });

  if (!error.config || !$instance.retry || $instance.__retryCount >= $instance.retry) return Promise.reject(error);
  $instance.__retryCount++;
  let backoff = new Promise(function (resolve) {
    setTimeout(function () {
      resolve();
    }, $instance.retryDelay || 1);
  });
  return backoff.then(function () {
    return $instance(error.config);
  });
  // return Promise.reject(error);
});

export default $instance;
